<?php

/**
 * This is the model class for table "url_class".
 *
 * The followings are the available columns in table 'url_class':
 * @property integer $classid
 * @property integer $parentid
 * @property string $classname
 * @property integer $displayorder
 * @property integer $sitenum
 * @property string $path
 * @property string $keywords
 * @property string $description
 * @property integer $create_at
 * @property integer $update_at
 * @property integer $level
 * @property string $classroot
 */
class UrlClass extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return UrlClass the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'url_class';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('classname', 'required'),
			array('parentid, displayorder, sitenum, create_at, update_at, level', 'numerical', 'integerOnly'=>true),
			array('classname', 'length', 'max'=>20),
			array('path', 'length', 'max'=>255),
			array('keywords', 'length', 'max'=>100),
			array('classroot', 'length', 'max'=>200),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('classid, parentid, classname, displayorder, sitenum, path, keywords, description, create_at, update_at, level, classroot', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'classid' => 'Classid',
			'parentid' => 'Parentid',
			'classname' => 'Classname',
			'displayorder' => 'Displayorder',
			'sitenum' => 'Sitenum',
			'path' => 'Path',
			'keywords' => 'Keywords',
			'description' => 'Description',
			'create_at' => 'Create At',
			'update_at' => 'Update At',
			'level' => 'Level',
			'classroot' => 'Classroot',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;
		$criteria->compare('classid',$this->classid);
		$criteria->compare('parentid',$this->parentid);
		$criteria->compare('classname',$this->classname,true);
		$criteria->compare('displayorder',$this->displayorder);
		$criteria->compare('sitenum',$this->sitenum);
		$criteria->compare('path',$this->path,true);
		$criteria->compare('keywords',$this->keywords,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('create_at',$this->create_at);
		$criteria->compare('update_at',$this->update_at);
		$criteria->compare('level',$this->level);
		$criteria->compare('classroot',$this->classroot,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * 获取子类
	 */
	public function getSubClass($parentid = 0,$criteria = ''){
		$parentid = intval($parentid);
		if(!$criteria){
			$criteria=new CDbCriteria;
			$criteria->select='*';
			$criteria->condition='parentid=:parentid';
			$criteria->order='displayorder ASC';
			$criteria->params=array(':parentid'=>$parentid);
		}
		$list = $this->findAll($criteria);
			$class_list = array();
			foreach ($list as $key=>$data)
			{
				$class_list[$data->getAttribute('classid')]= $data->getAttributes();
			}
		if(!count($class_list)){
			$class_list = false;
		}
		return $class_list;
	}
	
	/**
	 * 查找分类
	 */
	public function search_class($keyword = '')
	{
		 if(empty($keyword))
        {
            return array();
        }
		$condition = "classname like '%" . $keyword . "%' order by parentid";
		$search_rs = Yii::app()->db->createCommand()
						->select('classid')
					    ->from($this->tableName())
					    ->where($condition)
					    ->queryRow();
        if( !$search_rs )
        {
            return array();
        }

        $class = $this->get_class_list();
        $result = array();
        foreach( $search_rs as $row )
        {
            $path = array();
            $id_list = array();
            if( isset($class[$row['classid']]) )
            {
                $cur_class = $class[$row['classid']];
                while(1)
                {
                    array_unshift($path, $cur_class['classname']);
                    array_unshift($id_list, $cur_class['classid']);
                    if($cur_class['parentid'] == 0) //当是一级分类时 break
                    {
                        break;
                    }
                    $cur_class = $class[$cur_class['parentid']];
                }

                $result[] = array('key' => $row['classid'], 'value' => implode( '&raquo;', $path), 'id_list' => implode( ',', $id_list) );
            }
        }
        return $result;
	}
	
	/**
	 * @todo 返回所有分类
	 * @author 作者
	 */
	public function get_class_list()
	{
		$data = Yii::app()->db->createCommand()
								->select('*')
							    ->from($this->tableName())
							    ->order('displayorder ASC')
							    ->queryAll();
		$class_list = array();
        if( $data )
        {
            foreach ($data as $row)
            {
                $class_list[$row['classid']] = $row;
            }
            unset($data);
        }
		return $class_list;
	}
	
	/**
	 * @todo 返回分类路径
	 * @author 王汉
	 * @return array 类别路径数组
	 */
	public function getClassPath($classid)
	{
		$classid = intval($classid);
		$current_class = self::model()->findByPk($classid);
		$path_array = array();
		array_unshift($path_array,$current_class->classid);
		$parent_id = $current_class->parentid;
		while($parent_id !=0)
		{
			$tempCR = self::model()->findByPk($parent_id);
			array_unshift($path_array,$tempCR->classid);
			$parent_id = $tempCR->parentid;
		}
		return $path_array;
	}
	
	/**
	 * @todo 更新分类path
	 * @author 王汉
	 *
	 */
	public function updateClassPath($classid = 0)
	{
		if($classid == 0){
			$classid = $this->classid;
		}
		$currentClass = self::model()->findByPk($classid);
		$path_arr = $this->getClassPath($currentClass->classid);
		$path = implode('/', $path_arr);
		$currentClass->path = $path;
		$currentClass->save();
	}
	
	/**
	 *
	 * @todo 获取分类名称 可传入多个classId
	 * @param IntOrArray $classids 分类ID
	 * @param int $out_type 0=返回字符串 1=返回数组
	 * @param string $glue 分类连接符
	 * @author wanghan 王汉
	 */
	public function getClassNames($classids = 0,$out_type = 0 ,$glue = '>')
	{
		$ret_class_names = array();
		if($classids == 0){
			$classids = $this->classid;
		}
		if(!is_array($classids)){
			$classids = array($classids);
		}
		foreach ($classids as $classid){
			$tmp_model = self::model()->findByPk($classid);
			$ret_class_names[$tmp_model->classid] = $tmp_model->classname;
		}
		if($out_type == 1){
			return $ret_class_names;
		}
		if($out_type == 0){
			return implode($glue, $ret_class_names);
		}
	}
	/**
	 * This is invoked before the record is saved.
	 * @return boolean whether the record should be saved.
	 */
	protected function beforeSave()
	{
		if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
				$this->create_at=$this->update_at=time();
			}
			else
				$this->update_at=time();
			if(!$this->parentid){
				$this->parentid = 0;
			}
			if(!$this->displayorder){
				$this->displayorder = 100;
			}
			return true;
		}
		else
			return false;
	}
	
	/**
	 * 记录保存后的处理
	 */
	protected function afterSave()
	{
		parent::afterSave();
		//Tag::model()->updateFrequency($this->_oldTags, $this->tags);
	}
}